package com.lapula.crazyface.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

import android.content.Context;
import android.os.Environment;

import com.lapula.crazyface.Constants;

public class FileUtil {
	public static OutputStream getFileOutputStream(Context context, String filename) {
		boolean sdCardExist = Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED); // 判断sd卡是否存在
		if (sdCardExist) {
			File dir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + Constants.APP_PATH);
			if (!dir.exists()) {
				dir.mkdirs();
			}
			try {
				return new FileOutputStream(dir.getAbsolutePath() + "/" + filename);
			} catch (FileNotFoundException e) {
				e.printStackTrace();
				return null;
			}
		} else {
			try {
				return context.openFileOutput(filename, Context.MODE_WORLD_WRITEABLE);
			} catch (FileNotFoundException e) {
				e.printStackTrace();
				return null;
			}
		}
	}

	public static InputStream getFileInputStream(Context context, String filename) {
		boolean sdCardExist = Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED); // 判断sd卡是否存在
		if (sdCardExist) {
			String filepath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + Constants.APP_PATH + filename;
			File file = new File(filepath);
			if (file.exists()){
				try {
					return new FileInputStream(filepath);
				} catch (FileNotFoundException e) {
					e.printStackTrace();
					return null;
				}
			} else {
				return null;
			}
		} else {
			try {
				return context.openFileInput(filename);
			} catch (FileNotFoundException e) {
				e.printStackTrace();
				return null;
			}
		}
	}
}
